package com.szgd.service.personnel;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.szgd.dao.ecdata.personnel.CertificateMapper;
import com.szgd.dao.ecdata.personnel.EnterExitMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.HttpUtil;
import com.szgd.util.PropertiesUtil;
import com.szgd.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class EnterExitService extends SimulateBaseService {

    @Autowired
    EnterExitMapper enterExitMapper;
    @Autowired
    PersonnelInfoService personnelInfoService;
    @Autowired
    PersonnelFaceIdService personnelFaceIdService;
    private static Logger logger = Logger.getLogger(EnterExitService.class);
    private static long lastSybTime = 0;

    /**
     * 从其他系统数据插入
     * @param personId
     * @param passTime
     */
    public  int insertEnterExitFromOtherSystem(String personId,String passTime,int passFlag,String projectId,
                                               String workSiteId,String siteId,String gatherEquipId,String path)
    {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("personId",personId);
        paramsMap.put("siteId",siteId);
        Map<String, Object> personnelInfoMap = personnelInfoService.getPersonnelInfoByPersonId(paramsMap);
        String personnelId = null;
        if (personnelInfoMap != null)
        {
            personnelId = personnelInfoMap.get("id").toString();
        }else
        {
            logger.info("没有找到对应的人员，直接返回，不插入");
            return 0;//
        }
        paramsMap.put("personnelId",personnelId);
        paramsMap.put("passTime",passTime);
        paramsMap.put("passFlag",passFlag);
        paramsMap.put("projectId",projectId);
        paramsMap.put("workSiteId",workSiteId);
        paramsMap.put("siteId",siteId);
        paramsMap.put("gatherEquipId",gatherEquipId);
        paramsMap.put("path",path);

        if (passFlag == 2)//如果是离开闸机，获取上次进入记录ID，保存到此条离开记录
        {
            logger.info("passFlag标识是2，先获取进入记录");
            Map<String, Object> enterParamsMap = new HashMap<>();
            enterParamsMap.put("rownum",1);//获取最新一条
            enterParamsMap.put("personId",personId);
            enterParamsMap.put("passFlag",1);
            enterParamsMap.put("endPassTime",passTime);
            enterParamsMap.put("exitIdIsNull",1);
            enterParamsMap.put("passTimeSort",1);//1降序desc，0升序asc
            enterParamsMap.put("siteId",siteId);
            List<Map<String,Object>> list = enterExitMapper.getTopNEnterOrExitList(enterParamsMap);
            if (list != null && list.size() > 0)
            {
                Map<String,Object> enterRecordMap = list.get(0);
                String enterId = enterRecordMap.get("id").toString();
                paramsMap.put("enterId",enterId);
                paramsMap.put("updateTime",enterRecordMap.get("passTime"));
            }
        }else  if (passFlag == 1)//如果是进入闸机，获取此时间后第一条离开记录ID
        {
            logger.info("passFlag标识是1，先获取离开记录");
            Map<String, Object> enterParamsMap = new HashMap<>();
            enterParamsMap.put("rownum",1);//获取最新一条
            enterParamsMap.put("personId",personId);
            enterParamsMap.put("passFlag",2);
            enterParamsMap.put("beginPassTime",passTime);
            enterParamsMap.put("enterIdIsNull",1);
            enterParamsMap.put("passTimeSort",0);//1降序desc，0升序asc
            enterParamsMap.put("siteId",siteId);
            List<Map<String,Object>> list = enterExitMapper.getTopNEnterOrExitList(enterParamsMap);
            if (list != null && list.size() > 0)
            {
                Map<String,Object> exitRecordMap = list.get(0);
                String exitId = exitRecordMap.get("id").toString();
                paramsMap.put("exitId",exitId);
                paramsMap.put("updateTime",exitRecordMap.get("passTime"));
            }
        }
        logger.info("开始插入进出记录");
        enterExitMapper.insertEnterExit(paramsMap);
        logger.info("结束插入进出记录");
        if (passFlag == 2 && paramsMap.get("enterId") != null)//如果是离开闸机，此条离开记录插入后，把ID更新到上次进入记录
        {
            Map<String, Object> enterParamsMap = new HashMap<>();
            String exitId = paramsMap.get("id").toString();
            enterParamsMap.put("exitId",exitId);
            enterParamsMap.put("id",paramsMap.get("enterId"));
            enterParamsMap.put("updateTime",paramsMap.get("passTime"));
            enterExitMapper.updateEnterExit(enterParamsMap);
        }else  if (passFlag == 1 && paramsMap.get("exitId") != null)//如果是进入闸机，此条进入记录插入后，把ID更新到下次离开记录
        {
            Map<String, Object> exitParamsMap = new HashMap<>();
            String enterId = paramsMap.get("id").toString();
            exitParamsMap.put("enterId",enterId);
            exitParamsMap.put("id",paramsMap.get("exitId"));
            exitParamsMap.put("updateTime",paramsMap.get("passTime"));
            enterExitMapper.updateEnterExit(exitParamsMap);
        }
        logger.info("整个插入 过程完成！");
        return  Integer.parseInt(paramsMap.get("id").toString());
    }

    public Map<String, Object> getLastEnterOrExitInfo(Map<String, Object> paramsMap) {
        List<Map<String,Object>> enterExitList = enterExitMapper.getEnterOrExitList(paramsMap);
        if (enterExitList  != null && enterExitList.size() > 0)
            return enterExitList.get(0);
        else
            return  null;
    }

    public List<Map<String, Object>> getTopNEnterAndExitList(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        List<Map<String,Object>> enterExitList = enterExitMapper.getTopNEnterAndExitList(params);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();

                if (sEnterTime != null)
                {
                    enterExitMap.put("enterTime",sEnterTime.substring(0,16));
                }

                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }else
                {
                    enterExitMap.put("exitTime",sExitTime.substring(0,16));
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    /*String stayHours =  (day*24 + hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分";*/
                    enterExitMap.put("stayHours",stayHours);
                }


            }
        }
        return enterExitList;
    }


    /**
     * 以进入记录为准，获取进入记录信息，如果此进入记录有对应的离开记录，同时匹配离开记录。如果没有离开记录，则对应的离开记录信息为null
     * @param params
     * @return
     */
    public List<Map<String, Object>> getEnterAndExitList(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        String sortColumn = "SORT_TIME"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.personnel.EnterExitMapper.getEnterAndExitList", params,pageBounds);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }
            }
        }
        return enterExitList;
    }


    public List<Map<String, Object>> getTopNEnter_ExitList(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        List<Map<String,Object>> enterExitList = enterExitMapper.getTopNEnter_ExitList(params);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();

                if (sEnterTime.length() > 0)
                {
                    enterExitMap.put("enterTime",sEnterTime.substring(0,16));
                }

                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }else
                {
                    enterExitMap.put("exitTime",sExitTime.substring(0,16));
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    /*String stayHours =  (day*24 + hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分";*/
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }


            }
        }
        return enterExitList;
    }


    /**
     * 除了返回getEnterAndExitList的结果，同时返回没有对应进入的离开记录
     * @param params
     * @return
     */
    public List<Map<String, Object>> getEnter_ExitList(Map<String, Object> params) {

        //默认2天内数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -2);    //
        Date beginDate = calendar.getTime();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        params.put("enterDateFrom",df.format(beginDate));

        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        String sortColumn = "SORT_TIME"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.personnel.EnterExitMapper.getEnter_ExitList", params,pageBounds);
        if (enterExitList != null)
        {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }
            }
        }
        return enterExitList;
    }

    public List<Map<String, Object>> getEnter_ExitListNoPage(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        List<Map<String, Object>>  enterExitList = enterExitMapper.getEnter_ExitList(params);
        if (enterExitList != null) {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                String sex = enterExitMap.get("sex")==null?"":enterExitMap.get("sex").toString();
                if(sex != null && sex .length() > 0){
                    if(sex.equalsIgnoreCase("1")){
                        enterExitMap.put("sex","男");
                    }else if(sex.equalsIgnoreCase("0")){
                        enterExitMap.put("sex","女");
                    }
                }else{
                    enterExitMap.put("sex","");
                }
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();
                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }
            }
        }
        return enterExitList;
    }

    public int getEnterOrExitCount(String personId,String passTime)
    {
        Map<String, Object> params = new HashMap<>();
        params.put("personId",personId);
        params.put("passTime",passTime);
        return  enterExitMapper.getEnterOrExitCount(params);

    }

    public int getPersonnelBePresentCount(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        return  enterExitMapper.getBePresentCount(params);
    }

    public boolean synEnterExitRecord(String password,String ip,int passFlag,String projectId, String workSiteId,String siteId,String gatherEquipId){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        boolean result = false;
        logger.info("开始同步人员进出闸机数据!");
        String url = PropertiesUtil.get("PersonnelEnterExitRecordSynUrl");
        url = url.replace("{ip}",ip);
        logger.info("获取进出记录URL="+url);
        String pass = password;
        String paramPersonId = "-1";
        String length = "-1";
        String index = "0   ";
        String startTime = "0";
        String endTime = "0";

        if (lastSybTime == 0)//系统启动后首次，取当天凌晨时间戳
        {
            long now = System.currentTimeMillis() / 1000l;
            long daySecond = 60 * 60 * 24;
            long dayTime = now - (now + 8 * 3600) % daySecond;
            startTime = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochSecond(dayTime +1), ZoneId.systemDefault()));
        }else
        {
            startTime = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochSecond(lastSybTime/ 1000l +1), ZoneId.systemDefault()));
        }

        String requestParam = "pass="+pass+"&personId="+paramPersonId +"&length="+length+"&index="+index +"&startTime="+startTime+"&endTime="+endTime;
        logger.info("同步请求参数:"+requestParam);
        //发送 GET 请求
        String resultStr = HttpUtil.sendGet(url, requestParam);
        if (resultStr.length() == 0)
        {
            logger.info("访问小麦服务器失败，同步人员进出闸机数据失败!");
            return result;
        }
        JsonObject returnData = new JsonParser().parse(resultStr).getAsJsonObject();
        String success = returnData.get("success").getAsString();
        if(success.equalsIgnoreCase("true"))//调用结果成功
        {
            result = true;
            int total = returnData.getAsJsonObject("data").getAsJsonObject("pageInfo").get("total").getAsInt();
            if (total > 0)//如果有数据返回
            {
                JsonArray recordJsonArray = returnData.getAsJsonObject("data").getAsJsonArray("records");
                for (int i = 0; i < recordJsonArray.size(); i++) {
                    JsonObject recordJsonObject = recordJsonArray.get(i).getAsJsonObject();
                    String id = recordJsonObject.get("personId").getAsString();
                    String personId = recordJsonObject.get("personId").getAsString();
                    long time = recordJsonObject.get("personId").getAsLong();
                    String timeStr = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
                    int state = recordJsonObject.get("state").getAsInt();
                    int type = recordJsonObject.get("type").getAsInt();
                    if (type == 2)//陌生人或识别失败
                        continue;
                    if (personId.length()==0)
                    {
                        logger.info(id+"对应的人员Id为空，此条记录同时失败!");
                        continue;
                    }
                    int count = this.getEnterOrExitCount(personId,timeStr);
                    if (count == 0)//可以插入，如果大于0说明数据库已经存在，则跳过
                    {
                        int enterExitId = this.insertEnterExitFromOtherSystem(personId,timeStr,passFlag,projectId, workSiteId,siteId,gatherEquipId,null);
                    }
                    if (i==recordJsonArray.size()-1)//如果是最后一条
                    {
                        lastSybTime = time;//保存最近的记录时间
                    }
                }
            }else
            {
                logger.info("没有人员进出闸机数据!");
            }

        }else
        {
            logger.info("同步人员进出闸机数据失败!");
        }

        return result;
    }

    public int synEnterExitRecord_EX(String password,String ip,int passFlag,String siteId,
                                     String gatherEquipId,String sTime,String personId,String path){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        int result = -1;

        String pass = password;
        String paramPersonId = "-1";
        String length = "-1";
        String index = "0   ";
        String startTime = "0";
        String endTime = "0";

        long time = Long.parseLong(sTime);
        String timeStr = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
        int enterExitId = this.insertEnterExitFromOtherSystem(personId,timeStr,passFlag,null, null,siteId,gatherEquipId,path);
        result = enterExitId;
        return result;
    }

    public int insertEnterExitRecordFrom(String password,String ip,int passFlag,String siteId,
                                     String gatherEquipId,String sTime,String personId,String path){
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        long time = Long.parseLong(sTime);
        String timeStr = dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
        //int enterExitId = this.insertEnterExitFromOtherSystem(personId,timeStr,passFlag,null, null,siteId,gatherEquipId,path);
        String passTime = timeStr;
        String projectId = null;
        String workSiteId = null;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("personId",personId);
        paramsMap.put("siteId",siteId);
        List<Map<String, Object>>  personnelFaceIdList = personnelFaceIdService.getPersonnelFaceIdListNoPage(paramsMap);
        String personnelId = null;
        String personnelName = null;
        if (personnelFaceIdList != null && personnelFaceIdList.size() > 0)
        {
            personnelId = personnelFaceIdList.get(0).get("personnelId").toString();
            personnelName = personnelFaceIdList.get(0).get("personnelName").toString();
        }
        logger.info("开始插入原始进出记录表："+ip+"，人员名称："+personnelName+"，进出标识："+passFlag);
        paramsMap.put("personnelId",personnelId);
        paramsMap.put("passTime",passTime);
        paramsMap.put("passFlag",passFlag);
        paramsMap.put("projectId",projectId);
        paramsMap.put("workSiteId",workSiteId);
        paramsMap.put("siteId",siteId);
        paramsMap.put("gatherEquipId",gatherEquipId);
        paramsMap.put("path",path);
        enterExitMapper.insertEnterExitFrom(paramsMap);
        logger.info("结束插入原始进出记录表："+ip+"，人员名称："+personnelName+"，进出标识："+passFlag);
        return  Integer.parseInt(paramsMap.get("id").toString());

    }


    public List<Map<String,Object>> getEnterExitList(Map<String, Object> params){
        return enterExitMapper.getEnterExitList(params);
    }

    public List<Map<String,Object>> getEnterExitFromList(Map<String, Object> params){
        return enterExitMapper.getEnterExitFromList(params);
    }

    public void updateDataStatus(Map<String, Object> params){
        List<Map<String,Object>> list =  (List<Map<String,Object>>)params.get("list");
        for (int i = 0; i < list.size(); i++) {
            Map<String,Object> tempMap = list.get(i);
            enterExitMapper.updateDataStatus(tempMap);
        }

    }

    public List<Map<String, Object>> getEnterExitListForApp(Map<String, Object> params) {
        List<Map<String,Object>> enterExitList = enterExitMapper.getEnterExitListForApp(params);
        Integer enterExitCount = enterExitMapper.countElusivePeople(params);
        if (enterExitList != null) {
            SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                enterExitMap.put("EXcount",enterExitCount);
                String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
                String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();

                if (sEnterTime.length() > 0)
                {
                    enterExitMap.put("enterTime",sEnterTime.substring(0,16));
                }

                if (sExitTime == null || sExitTime.length() ==0)
                {
                    sExitTime = sd.format(new Date());
                }else
                {
                    enterExitMap.put("exitTime",sExitTime.substring(0,16));
                }
                if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
                {
                    long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
                    long nh = 1000 * 60 * 60;// 一小时的毫秒数
                    long nm = 1000 * 60;// 一分钟的毫秒数

                    long lEnterTime = 0;
                    long lExitTime = 0;
                    try {
                        lEnterTime = sd.parse(sEnterTime).getTime();
                        lExitTime = sd.parse(sExitTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = lExitTime - lEnterTime;
                    long day = diff / nd;// 计算差多少天
                    long hour = diff % nd / nh + day * 24;// 计算差多少小时
                    long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

                    String stayHours =  day + "天" + (hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分" ;
                    if (day==0)
                        stayHours =  (hour - day * 24) + "时"
                                + (min - day * 24 * 60) + "分" ;
                    enterExitMap.put("stayHours",stayHours);
                }else
                {
                    enterExitMap.put("stayHours","");
                }

            }
        }
        return enterExitList;
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("name","姓名");
        fieldMapping.put("sex","性别");
        fieldMapping.put("workTypeName","岗位");
        fieldMapping.put("enterTime","进入工地时间");
        fieldMapping.put("exitTime","离开工地时间");
        fieldMapping.put("stayHours","停留时长");
        fieldMapping.put("siteName","所属站点");

        return fieldMapping;
    }

    public Map<String, String> getLeaderFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("NAME","姓名");
        fieldMapping.put("WORK_TYPE_NAME","岗位");
        fieldMapping.put("PASS_MONTH","月份");
        fieldMapping.put("DAYS","进场天数");
        fieldMapping.put("SITE_NAME","所属站点");

        return fieldMapping;
    }

    public Map<String, String> getMNFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("NAME","姓名");
        fieldMapping.put("WORK_TYPE_NAME","岗位");
        fieldMapping.put("PASS_MONTH","月份");
        fieldMapping.put("DAYS","进场天数");
        fieldMapping.put("SITE_NAME","所属站点");

        return fieldMapping;
    }

    /*
    app-获取每个站点的前十条记录
     */
    public List<List<Map<String,Object>>> getTop10Enter_ExitList(Map<String, Object> params) {
        List<Map<String,Object>> enterExitList = enterExitMapper.getTop10Enter_ExitList(params);
        List<List<Map<String,Object>>> result = new ArrayList<>();
        if (enterExitList != null && enterExitList.size() > 0) {
            String siteId = enterExitList.get(0).get("siteId").toString();
            List<Map<String,Object>> tempList = new ArrayList<>();
            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                this.computeTime(enterExitMap);
                String siteIdCur = enterExitList.get(i).get("siteId").toString();
                if(siteIdCur.equalsIgnoreCase(siteId)){
                    tempList.add(enterExitMap);
                }else{
                    result.add(tempList);
                    tempList = new ArrayList<>();
                    siteId = siteIdCur;
                    tempList.add(enterExitMap);
                }
            }
            result.add(tempList);
        }
        return result;
    }

    public List<String> getEnterExitListCount(Map<String, Object> params){
        List<String> result = new ArrayList<>();
        List<Map<String,Object>> list = enterExitMapper.getEnterExitListCount(params);
        for(Map<String,Object> map : list){
            String count = map.get("COUNT")==null?"":map.get("COUNT").toString();
            result.add(count);
        }
        return result;
    }

    public List<String> getPresentPersonCount(Map<String, Object> params){
        List<String> result = new ArrayList<>();
        List<Map<String,Object>> list = enterExitMapper.getPresentPersonCount(params);
        for(Map<String,Object> map : list){
            String count = map.get("COUNT")==null?"":map.get("COUNT").toString();
            result.add(count);
        }
        return result;
    }

    private void computeTime(Map<String, Object> enterExitMap){
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sEnterTime = enterExitMap.get("enterTime")==null?"":enterExitMap.get("enterTime").toString();
        String sExitTime = enterExitMap.get("exitTime")==null?"":enterExitMap.get("exitTime").toString();

        if (sEnterTime.length() > 0)
        {
            enterExitMap.put("enterTime",sEnterTime.substring(0,16));
        }

        if (sExitTime == null || sExitTime.length() ==0)
        {
            sExitTime = sd.format(new Date());
        }else
        {
            enterExitMap.put("exitTime",sExitTime.substring(0,16));
        }
        if (sEnterTime.length()  > 0 && sExitTime.length() > 0)
        {
            long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
            long nh = 1000 * 60 * 60;// 一小时的毫秒数
            long nm = 1000 * 60;// 一分钟的毫秒数

            long lEnterTime = 0;
            long lExitTime = 0;
            try {
                lEnterTime = sd.parse(sEnterTime).getTime();
                lExitTime = sd.parse(sExitTime).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long diff = lExitTime - lEnterTime;
            long day = diff / nd;// 计算差多少天
            long hour = diff % nd / nh + day * 24;// 计算差多少小时
            long min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟

            String stayHours =  day + "天" + (hour - day * 24) + "时"
                    + (min - day * 24 * 60) + "分" ;
            if (day==0)
                stayHours =  (hour - day * 24) + "时"
                        + (min - day * 24 * 60) + "分" ;
                    /*String stayHours =  (day*24 + hour - day * 24) + "时"
                            + (min - day * 24 * 60) + "分";*/
            enterExitMap.put("stayHours",stayHours);
        }else
        {
            enterExitMap.put("stayHours","");
        }
    }

    public List<Map<String, Object>> getLeaderRecordNoPage(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        List<Map<String, Object>>  enterExitList = enterExitMapper.getLeaderRecord(params);
        return enterExitList;
    }

    public List<Map<String, Object>> getLeaderRecord(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        String sortColumn = "pass_month"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.personnel.EnterExitMapper.getLeaderRecord", params,pageBounds);
        return enterExitList;
    }


    public List<Map<String, Object>> getMNRecordNoPage(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        String queryType = params.get("queryType")==null?"":params.get("queryType").toString().replace("null","");
        if(queryType.length() == 0){
            params.put("queryType",null);
        }else if(queryType.equalsIgnoreCase("Morning")){
            params.put("queryType","6:00-9:00");
        }else if(queryType.equalsIgnoreCase("Night")){
            params.put("queryType","18:00-24:00");
        }
        List<Map<String, Object>>  enterExitList = enterExitMapper.getMNRecord(params);
        return enterExitList;
    }

    public List<Map<String, Object>> getMNRecord(Map<String, Object> params) {
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString().replace("null","");
        if(siteId.length() == 0){
            params.put("siteId",null);
        }
        String workType = params.get("workType")==null?"":params.get("workType").toString().replace("null","");
        if(workType.length() > 0){
            List<String> workTypeList = Arrays.asList(workType.split(","));
            String workTypes = "IN ('" + workTypeList.get(0) + "'";
            for(int i=1; i<workTypeList.size(); i++){
                workTypes += ",'" + workTypeList.get(i) + "'";
            }
            workTypes += ")";
            params.put("workTypes",workTypes);
        }
        String queryType = params.get("queryType")==null?"":params.get("queryType").toString().replace("null","");
        if(queryType.length() == 0){
            params.put("queryType",null);
        }else if(queryType.equalsIgnoreCase("Morning")){
            params.put("queryType","6:00-9:00");
        }else if(queryType.equalsIgnoreCase("Night")){
            params.put("queryType","18:00-24:00");
        }
        String sortColumn = "pass_month"; //默认的排序列
        String sortType = "desc";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  enterExitList = getSqlSession().selectList("com.szgd.dao.ecdata.personnel.EnterExitMapper.getMNRecord", params,pageBounds);
        return enterExitList;
    }

    public Map<String, Object> app_getEERecord(Map<String, Object> params) {
        params.put("isApp","1");
        List<Map<String,Object>> enterExitList = enterExitMapper.app_getEEList(params);
        List<Map<String,Object>> enterExitCount = enterExitMapper.app_getEECount(params);
        if (enterExitList != null) {
            for (int i = 0; i < enterExitList.size(); i++) {
                Map<String, Object> enterExitMap = enterExitList.get(i);
                this.computeTime(enterExitMap);
            }
        }
        Map<String, Object> res = new HashMap<>();
        res.put("list",enterExitList);
        res.put("count",enterExitCount.size());
        return res;
    }

    public Map<String, Object> app_getLeaderRecord(Map<String, Object> params) {
        params.put("isApp","1");
        List<Map<String,Object>> enterExitList = enterExitMapper.app_getLeaderList(params);
        List<Map<String,Object>> enterExitCount = enterExitMapper.app_getLeaderCount(params);
        Map<String, Object> res = new HashMap<>();
        res.put("list",enterExitList);
        res.put("count",enterExitCount.size());
        return res;
    }

    public Map<String, Object> app_getMNRecord(Map<String, Object> params) {
        params.put("isApp","1");
        String queryType = params.get("queryType")==null?"":params.get("queryType").toString().replace("null","");
        if(queryType.length() == 0 || queryType.equalsIgnoreCase("all")){
            params.put("queryType",null);
        }else if(queryType.equalsIgnoreCase("Morning")){
            params.put("queryType","6:00-9:00");
        }else if(queryType.equalsIgnoreCase("Night")){
            params.put("queryType","18:00-24:00");
        }
        List<Map<String,Object>> enterExitList = enterExitMapper.app_getMNList(params);
        List<Map<String,Object>> enterExitCount = enterExitMapper.app_getMNCount(params);
        Map<String, Object> res = new HashMap<>();
        res.put("list",enterExitList);
        res.put("count",enterExitCount.size());
        return res;
    }
}
